<?php

namespace app\common\job;


use app\common\model\goods\GoodsModel;
use app\common\model\goods\GoodsSpecModel;
use app\common\model\order\OrderAction;
use app\common\model\order\OrderModel;
use app\common\model\order\OrderUniqueModel;
use think\queue\Job;

/**
 * 下单后操作
 */

class OrderAfterAutoOper
{
    /**
     * 下单后未支付自动关闭订单操作
     */
    public function NoPayAutoCloseOrderOper(Job $job, $data)
    {
        try {
            // 重新查询订单
            \think\Log::write('queue-' . get_class() . '-NoPayAutoCloseOrderOper' . '：执行成功,参数:'.JsonEn($data));
            $orderUnique = OrderUniqueModel::get($data['order_id']);

            if ($orderUnique && $orderUnique->is_pay == 0) {
                \think\Db::transaction(function () use ($orderUnique, $data) {
                    // 关闭订单
                    $orderUnique->is_pay = -1;
                    $orderUnique->updatetime = time();
                    $orderUnique->save();
                    OrderModel::where(['unique_order_no' => $orderUnique->unique_order_no])->update([
                        'status' => 5,
                        'is_close' => 1,
                        'close_time' => time(),
                    ]);
                    // 库存回滚
                    if(!empty($data['goods'])){
                        foreach ($data['goods'] as $value){
                            $goods = GoodsModel::get($value['goods_id']);
                            if($goods->stock_type == 'place'){
                                GoodsModel::stockRollback($value['goods_id'],$value['goods_spec_id'],$value['num']);
                            }
                        }
                    }

                    $orders = OrderModel::where(['unique_order_no' => $orderUnique->unique_order_no])->select();

                    // 退回优惠券
                    if($data['user_coupon_id'] > 0){
                        \app\common\model\UserCouponModel::where(['id' => $data['user_coupon_id']])->update(['status' => 1, 'usetime' => '']);
                        foreach ($orders as $order){
                            OrderAction::operAdd($order, null, null, 'system', '订单取消退回优惠券');
                        }
                    }
                    foreach ($orders as $order){
                        OrderAction::operAdd($order, null, null, 'system', '系统自动失效订单');
                    }
                });
            }
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-NoPayAutoCloseOrderOper' . '：执行失败，参数:'.JsonEn($data).',错误信息：' . $e->getMessage());
        }
    }


    /**
     * 商品库存自动上下架校验操作
     */
    public function GoodStockCheckOper(Job $job, $data)
    {
        try {
            // 重新查询商品信息
            \think\Log::write('queue-' . get_class() . '-GoodStockCheckOper' . '：执行成功,参数:'.JsonEn($data));
            $goods = GoodsModel::get($data['goods_id']);

            if ($goods) {
                \think\Db::transaction(function () use ($goods, $data) {
                    // 查询商品库存信息
                    $totalGoodStock = GoodsSpecModel::where(['goods_id' => $goods->id])->whereNull('deletetime')->sum('spec_stock');
                    if($totalGoodStock <= 0){
                        // 下架商品
                        $goods->status = 'down';
                        $goods->updatetime = time();
                        $goods->save();
                    }else{
                        if($goods->status != 'up'){
                            // 上架商品
                            $goods->status = 'up';
                            $goods->updatetime = time();
                            $goods->save();
                        }
                    }
                });
            }
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-GoodStockCheckOper' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

}